import datetime
import json
class BillManagementSystem:
    def __init__(self):
        #初始化账单存储为空
        self.IncomeBills = []
        self.OutBills = []
        self.load_data()

    def load_data(self):
        try:
            with open('income_bills.json', 'r') as f:
                self.IncomeBills = json.load(f)
            with open('out_bills.json', 'r') as f:
                self.OutBills = json.load(f)
        except FileNotFoundError:
            # 如果文件不存在，则初始化为空列表
            self.IncomeBills = []
            self.OutBills = []

    def save_data(self):
        with open('income_bills.json', 'w') as f:
            json.dump(self.IncomeBills, f)
        with open('out_bills.json', 'w') as f:
            json.dump(self.OutBills, f)
    def RecordIncome(self):
        while True:
            try:
                date = input("日期（YYYY-MM-DD）：")
                datetime.datetime.strptime(date, "%Y-%m-%d")  # 验证日期格式
                amount = float(input("金额："))
                if amount <= 0:
                    raise ValueError("金额必须为正数")
                kind = input("类别（如工资、奖金等）：")
                remark = input("备注：")
                self.IncomeBills.append({  # 利用字典和列表嵌套存储记录，方便后面操作
                    "date": date,
                    "amount": amount,
                    "kind": kind,
                    "remark": remark
                })
                print("收入已成功记录！")
                input("按任意键返回主菜单..")
                break  # 成功记录后退出循环
            except ValueError as e:
                print(f"输入错误：{e}")
        self.save_data()

    def RecordOut(self):
        while True:
            try:
                date = input("日期（YYYY-MM-DD）：")
                datetime.datetime.strptime(date, "%Y-%m-%d")  # 验证日期格式
                amount = float(input("金额："))
                if amount <= 0:
                    raise ValueError("金额必须为正数")
                kind = input("类别（如餐饮、交通、购物等）：")
                remark = input("备注：")
                self.OutBills.append({
                    "date": date,
                    "amount": amount,
                    "kind": kind,
                    "remark": remark
                })
                print("支出已成功记录！")
                input("按任意键返回主菜单..")
                break  # 成功记录后退出循环
            except ValueError as e:
                print(f"输入错误：{e}")
        self.save_data()

    def ShowAllBills(self):
        if not self.IncomeBills and not self.OutBills:
            print("当前没有账单记录！")
            return
        print("所有账单：")
        print("收入：")
        for bill in self.IncomeBills:
            print(f"日期：{bill['date']} 金额：{bill['amount']} 类别：{bill['kind']} 备注：{bill['remark']}")
        print("支出：")
        for bill in self.OutBills:
            print(f"日期：{bill['date']} 金额：{bill['amount']} 类别：{bill['kind']} 备注：{bill['remark']}")

    def ShowBills(self):
        while True:
            print("请选择查询方式：")
            print("1. 按日期范围查询")
            print("2. 按类别查询")
            print("3. 返回主菜单")
            choice = input("请输入选项序号：")
            if choice == "1":
                start_date = input("起始日期（YYYY-MM-DD）：")
                end_date = input("结束日期（YYYY-MM-DD）：")
                self.DateRange(start_date, end_date)
            elif choice == "2":
                kind = input("请输入类别：")
                self.Kind(kind)
            elif choice == "3":
                break
            else:
                print("无效选项，请重新输入！")

    def DateRange(self, start_date, end_date):  # 按日期范围查询
        find_incomes = [bill for bill in self.IncomeBills if bill['date'] >= start_date and bill['date'] <= end_date]
        find_out = [bill for bill in self.OutBills if bill['date'] >= start_date and bill['date'] <= end_date]
        if not find_incomes and not find_out:
            print("没有找到符合条件的账单记录！")
            return
        print("查询结果：")
        print("收入：")
        for bill in find_incomes:
            print(f"日期：{bill['date']} 金额：{bill['amount']} 类别：{bill['kind']} 备注：{bill['remark']}")
        print("支出：")
        for bill in find_out:
            print(f"日期：{bill['date']} 金额：{bill['amount']} 类别：{bill['kind']} 备注：{bill['remark']}")

    def Kind(self, kind):  # 按类别查询
        finded_incomes = [bill for bill in self.IncomeBills if bill['kind'] == kind]
        finded_out = [bill for bill in self.OutBills if bill['kind'] == kind]
        if not finded_incomes and not finded_out:
            print("没有找到符合条件的账单记录！")
            return
        print("查询结果：")
        print("收入：")
        for bill in finded_incomes:
            print(f"日期：{bill['date']} 金额：{bill['amount']} 类别：{bill['kind']} 备注：{bill['remark']}")
        print("支出：")
        for bill in finded_out:
            print(f"日期：{bill['date']} 金额：{bill['amount']} 类别：{bill['kind']} 备注：{bill['remark']}")

    def main(self):
        while True:
            print("=================================")
            print("欢迎使用个人账单管理系统")
            print("=================================")
            print("请选择操作：")
            print("1. 记录收入")
            print("2. 记录支出")
            print("3. 查看所有账单")
            print("4. 查询账单")
            print("5. 退出系统")
            choice = input("请输入选项序号：")
            # 根据选项进入不同的功能
            if choice == "1":
                self.RecordIncome()
            elif choice == "2":
                self.RecordOut()
            elif choice == "3":
                self.ShowAllBills()
            elif choice == "4":
                self.ShowBills()
            elif choice == "5":
                print("感谢使用，再见！")
                break
            else:
                print("无效选项，请重新输入！")

# 创建对象,并进入主菜单
bill = BillManagementSystem()
bill.main()